from flask import Flask
from flask import request
from flask import make_response
from flask import render_template
import json
import os
import smtplib
from email.mime.text import MIMEText

def send_email(email,num):
    msg_from = 'chenguiying5@163.com'  # 发送方邮箱
    passwd = 'ITQGNUYTXTVOZXPU'  # 填入发送方邮箱的授权码
    msg_to = email  # 收件人邮箱
    subject = "打卡代理服务取消提醒"  # 主题
    content = "您的学号("+num+")已取消了打卡代理服务，请确保是本人操作"  # 正文
    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['From'] = msg_from
    msg['To'] = msg_to
    s = smtplib.SMTP_SSL("smtp.163.com", 465)  # 邮件服务器及端口号
    s.login(msg_from, passwd)
    s.sendmail(msg_from, msg_to, msg.as_string())
    print("发送成功")


app=Flask(__name__)
def verifyData(postdata):
    try:
        jsonDict=json.loads(postdata)
    except json.decoder.JSONDecodeError:
        return "打卡数据格式出错，请检查是否完整复制打卡数据"
    except:
        return "未知错误，请重新尝试或者联系管理员\n管理员VX：chenguiying5"
    return True

@app.route("/healthAgent",methods=["POST"])
def healthAgent():
    num=request.form["number"]
    postdata=request.form["formData"]
    email=request.form["sendEmail"]
    psd=request.form["psd"]
    result=verifyData(postdata)
    # print(postdata,email)
    if len(num)!=10:
        return "学号格式错误，请检查后重新提交"
    if result==True:
        f=open("num.txt","r")
        num_list=f.readlines()
        f.close()
        for nu in num_list:
            nu=nu.strip("\n")
            if nu==num:
                return "该用户已提交过打卡，请勿重复提交"
        f=open("num.txt","a")
        f.write(num+"\n")
        f.close()
        f=open(num+".txt","w")
        f.write(email+"\n"+postdata+"\n"+psd+"\n")
        f.close()
        return "打卡数据已成功提交"
    else:
        return result


@app.route("/healthCancel",methods=['POST'])
def healthCancel():
    num=request.form['cancelNum']
    ppsd=request.form['ppsd']
    flag=1
    error=0
    if len(num)!=10:
        return "学号格式错误，请检查后重新提交"
    f = open("num.txt", "r")
    lis = f.readlines()
    f.close()
    f1 = open("num.txt", "w")
    for li in lis:
        li = li.strip("\n")
        if num != li:
            f1.write(li + "\n")
        else:
            f2=open(num+".txt","r")
            ii=f2.readlines()
            f2.close()
            if ii[2].strip("\n")==ppsd:
                flag=0
            else:
                f1.write(li+"\n")
                error=1
    f1.close()
    if error:
        return "保护密码错误"
    if flag:
        return "该学号未提交过打卡代理"
    f=open(num+".txt","r")
    ll=f.readlines()
    f.close()
    em=ll[0]
    send_email(em,num)

    os.remove(num+".txt")
    return "取消代理打卡成功"

if __name__ == '__main__':
    app.run(host="0.0.0.0",port=7070)
